//
//  RABookrackCell.m
//  ReadApp
//
//  Created by 飞猪 on 2018/11/7.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "RABookrackCell.h"
#import "RABookFaceModel.h"
#import "RABookDetailModel.h"

@interface RABookrackCell ()
@property (nonatomic, strong) UIButton *deleteBtn;
@property (nonatomic, strong) UILongPressGestureRecognizer *longGes;
@end

@implementation RABookrackCell

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    [self createViews];
  }
  return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
  self = [super initWithCoder:coder];
  if (self) {
    [self createViews];
  }
  return self;
}

#pragma mark - CreateViews
- (void)createViews {
  self.backgroundColor = [UIColor whiteColor];
  
  [self.contentView addSubview:self.titleImg];
  [self.titleImg mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.mas_equalTo(self);
  }];
  
  [self.contentView addSubview:self.deleteBtn];
  [self.deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.right.mas_equalTo(self);
    make.size.mas_equalTo(CGSizeMake(32, 32));
  }];
  
  self.longGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
  [self addGestureRecognizer:self.longGes];
}

- (void)longPress:(UIGestureRecognizer *)ges {
  
  //直接return掉，不在开始的状态里面添加任何操作，则长按手势就会被少调用一次了
  if (ges.state != UIGestureRecognizerStateBegan) {
    return;
  }
  
  //下面写上想要执行的操作
  if (self.longPressCallback) {
    self.longPressCallback();
  }
  
}

- (void)deleteClick {
  if (self.DeleteCallback) {
    self.DeleteCallback(_detailModel);
  }
}

#pragma mark - Setter

- (void)setModel:(RABookFaceModel *)model {
  _model = model;
  
  [self.titleImg sd_setImageWithURL:[NSURL URLWithString:model.iconUrl] placeholderImage:[UIImage imageNamed:@"default_placeImage"]]; 
}

- (void)setDetailModel:(RABookDetailModel *)detailModel {
  _detailModel = detailModel;
  
  [self.titleImg sd_setImageWithURL:[NSURL URLWithString:_detailModel.bookCover] placeholderImage:[UIImage imageNamed:@"default_placeImage"]];
  
  if (_detailModel.isDelegate) {
    self.deleteBtn.hidden = NO;
  }
  else {
    self.deleteBtn.hidden = YES;
  }
}

#pragma mark - Lazyload
- (UIImageView *)titleImg {
  if (!_titleImg) {

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
    imageView.userInteractionEnabled = NO;

    _titleImg = imageView;
  }
  return _titleImg;
}

- (UIButton *)deleteBtn {
  if (!_deleteBtn) {
    _deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_deleteBtn setImage:[UIImage imageNamed:@"book_delete"] forState:UIControlStateNormal];
//    [_deleteBtn sizeToFit];
    [_deleteBtn addTarget:self action:@selector(deleteClick) forControlEvents:UIControlEventTouchUpInside];
    _deleteBtn.hidden = YES;
  }
  return _deleteBtn;
}

@end
